package com.gk.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gk.study.entity.BClassification;
import com.gk.study.entity.BThing;
import com.gk.study.entity.Home;
import com.gk.study.mapper.BClassificationMapper;
import com.gk.study.mapper.BThingMapper;
import com.gk.study.mapper.HomeMapper;
import com.gk.study.service.HomeService;
import com.gk.study.utils.CacheClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service
public class HomeServiceImpl extends ServiceImpl<HomeMapper, Home> implements HomeService {

    @Autowired
    private HomeMapper homeMapper;
    @Autowired
    private BThingMapper thingMapper;
    @Resource
    private CacheClient cacheClient;

    public List<Home> getList(String keyword){
        if (keyword==null){
            List<Home> list = homeMapper.list();
            return list;
        }else {
            List<Home> list = homeMapper.list(keyword);
            return list;
        }

    }
    @Override
    public List<Home> getHomeList(String keyword, String sort, String c, String tag) {
        QueryWrapper<Home> queryWrapper = new QueryWrapper<>();
        // 搜索
        // 如果keyword不为空，进行title的模糊查询
        queryWrapper.like(StringUtils.isNotBlank(keyword), "title", keyword);
        // 排序
        // 根据sort的值进行排序，如果sort为'recent'按创建时间降序排列，
        // 如果sort为'hot'或'recommend'按pv降序排列，
        // 否则默认按创建时间降序排列
        if (StringUtils.isNotBlank(sort)) {
            if (sort.equals("recent")) {
                queryWrapper.orderBy(true, false, "create_time");
            } else if (sort.equals("hot") || sort.equals("recommend")) {
                queryWrapper.orderBy(true, false, "pv");
            }
        } else {
            queryWrapper.orderBy(true, false, "create_time");
        }
        // 分类筛选
        if (StringUtils.isNotBlank(c) && !c.equals("-1")) {
            // 查询符合分类的thingId
            QueryWrapper<BThing> bThingQueryWrapper = new QueryWrapper<>();
            bThingQueryWrapper.select("id").eq("classification_id", c);
            List<Integer> thingIds = thingMapper.selectList(bThingQueryWrapper)
                    .stream()
                    .map(BThing::getId)
                    .collect(Collectors.toList());

            // 如果thingIds不为空，则根据thingId筛选Home表
            if (!thingIds.isEmpty()) {
                QueryWrapper<Home> homeQueryWrapper = new QueryWrapper<>();
                homeQueryWrapper.select("id")
                        .in("thing_id", thingIds);

                // 获取所有符合条件的Home记录的id
                List<Long> homeIds = homeMapper.selectList(homeQueryWrapper)
                        .stream()
                        .map(Home::getId)
                        .collect(Collectors.toList());

                // 如果homeIds不为空，则根据homeIds筛选Home表
                if (!homeIds.isEmpty()) {
                    queryWrapper.in("id", homeIds);
                } else {
                    // 如果homeIds为空，则返回空列表或采取其他适当的处理方式
                    return Collections.emptyList();
                }
            } else {
                // 如果thingIds为空，则返回空列表或采取其他适当的处理方式
                return Collections.emptyList();
            }
        }

        // 获取满足条件的Home列表
        List<Home> homes = homeMapper.selectList(queryWrapper);
        // tag筛选
        if (StringUtils.isNotBlank(tag)) {
            List<Home> filteredHomes = new ArrayList<>();
            QueryWrapper<BThing> bThingQueryWrapper = new QueryWrapper<>();
            bThingQueryWrapper.eq("tag_id", tag);
            List<BThing> bThingList = thingMapper.selectList(bThingQueryWrapper);

            for (Home home : homes) {
                for (BThing bThing : bThingList) {
                    if (home.getThingId() == bThing.getId()) {
                        filteredHomes.add(home);
                        break;
                    }
                }
            }

            homes = filteredHomes;
        }
        // 附加tag信息
        for (Home home : homes) {
            QueryWrapper<BThing> bThingQueryWrapper = new QueryWrapper<>();
            bThingQueryWrapper.eq("id", home.getThingId());
            List<BThing> bThings = thingMapper.selectList(bThingQueryWrapper);
            List<Integer> tags = bThings.stream().map(BThing::getTagId).collect(Collectors.toList());
            home.setTags(tags);
        }
        return homes;
    }

    @Override
    public Home getHomeById(String id) {
        Home home = cacheClient.queryWithPassThrough("home", id, Home.class, key -> homeMapper.selectById(key), 1L, TimeUnit.MINUTES);
        return home;
//        Home home = homeMapper.selectById(id);
//        return home;
    }
    // 心愿数加1
    @Override
    public void addWishCount(String homeId) {
        Home home = homeMapper.selectById(homeId);
        home.setWishCount(String.valueOf(Integer.parseInt(home.getWishCount()) + 1));
        homeMapper.updateById(home);
    }
    @Override
    public void addCollectCount(String thingId) {
        Home home = homeMapper.selectById(thingId);
        home.setCollectCount(String.valueOf(Integer.parseInt(home.getCollectCount()) + 1));
        homeMapper.updateById(home);
    }
}

